package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Font;

public class SingleChatServer extends JFrame implements Runnable{

	ServerSocket server = null;
	Socket socket = null;
	boolean threadFlag = true;
	BufferedReader receive = null;
	BufferedWriter send = null;
	StringBuilder data = new StringBuilder();

	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JButton btnStart;
	private JButton btnStop;
	private JTextField message;
	private JButton btnSend;
	private JScrollPane scrollPane;
	private JTextPane result;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					SingleChatServer frame = new SingleChatServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SingleChatServer() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				serverStop();
			}
		});
		setTitle("Single Chat Server");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 445, 455);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
		
		try{
			InetAddress ia = InetAddress.getLocalHost();
			String title = "서버IP:" + ia.getHostAddress();
			title += " / Port : 4444";
			setTitle(title);
		}catch(Exception ex){
			
		}
	}


	public void serverStart(){
		try{
			btnStart.setEnabled(false);
			btnStop.setEnabled(true);
			dataSet("<b>서버가 시작되었습니다.</b>");

			Thread t = new Thread(this);
			t.start();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void serverStop(){
		threadFlag=false;
		try{
			send.write("\tserverdown");
			send.newLine();
			send.flush();
		
		}catch(Exception ex){
			
		}
		dataSet("zzzz");
		
	}
	
	@Override
	public void run() {
		try{
			server = new ServerSocket(4444);
			socket = server.accept();
			dataSet("클라이언트가 접속되었습니다.");
			
			OutputStream os = socket.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			send = new BufferedWriter(osw);
			
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			receive = new BufferedReader(isr);
			
			threadFlag = true;
			while(threadFlag){
				String str = receive.readLine();
				if(str.equals("\tserverdown")){
					threadFlag = false;
				}else if(str.equals("\tkill")){
					threadFlag = false;
					sendMsg(str);
				}else{
					dataSet("<img src='file:\\P:\\workspace\\과정진행\\1403\\1403\\img1.png'><font color='blue'>" + str + "</font>");

				}
			}
			
			dataSet("<font color='red'>서버가 중지되었습니다.</font>");
			btnStart.setEnabled(true);
			btnStop.setEnabled(false);
			
			receive.close();
			isr.close();
			is.close();
			
			send.close();
			osw.close();
			os.close();
			
			socket.close();
			server.close();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	
	public void dataSet(String str){
		data.append(str);
		data.append("<br/>");
		result.setText(data.toString());
	}
	
	public void sendMsg(String str){
		try{
			send.write(str);
			send.newLine();
			send.flush();
			dataSet("<img src='file:\\P:\\workspace\\과정진행\\1403\\1403\\img2.png'><font color='blue'>" + str + "</font>");
		}catch(Exception ex){
			
		}
	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getBtnStart());
			panel.add(getBtnStop());
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getMessage(), BorderLayout.CENTER);
			panel_1.add(getBtnSend(), BorderLayout.EAST);
		}
		return panel_1;
	}
	private JButton getBtnStart() {
		if (btnStart == null) {
			btnStart = new JButton("서버시작");
			btnStart.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					serverStart();
				}
			});
		}
		return btnStart;
	}
	private JButton getBtnStop() {
		if (btnStop == null) {
			btnStop = new JButton("서버종료");
			btnStop.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					serverStop();
				}
			});
		}
		return btnStop;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent ev) {
					if(ev.getKeyCode() == KeyEvent.VK_ENTER){
						String str = message.getText();
						sendMsg(str);
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JButton getBtnSend() {
		if (btnSend == null) {
			btnSend = new JButton("메시지전송");
			btnSend.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					String str = message.getText();
					sendMsg(str);
				}
			});
		}
		return btnSend;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setFont(new Font("굴림", Font.PLAIN, 16));
			result.setContentType("text/html");
		}
		return result;
	}
}
